package com.atguigu.controller;

import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/houseImage")
public class HouseImageController {
    @DubboReference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Map map){
        map.put("houseId", houseId);
        map.put("type", type);
        return "house/upload";
    }
    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId,
                         @PathVariable Integer type,
                         @RequestParam("file")MultipartFile[] files) throws IOException {
        for (MultipartFile file : files) {
            //上传图片到七牛云
            String fileName = UUID.randomUUID().toString();
            QiniuUtil.upload2Qiniu(file.getBytes(),fileName );
            //上传图片到数据库
            HouseImage houseImage = new HouseImage();
            houseImage.setHouseId(houseId);
            houseImage.setType(type);
            houseImage.setImageName(fileName);
            houseImage.setImageUrl("http://rod3a7eig.hn-bkt.clouddn.com/"+fileName);
            houseImageService.insert(houseImage);
        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId,@PathVariable Integer id){
        HouseImage houseImage = houseImageService.getById(id);
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());
        houseImageService.delete(id);

        return "redirect:/house/show/" + houseId;
    }
}
